import React, { Component } from 'react';
import { Map, MouseTool } from 'react-amap';
import { Form, Button, Badge, Modal, Row, Col, Input, Table, Select } from 'antd';
import car from '../../assets/car.png';
import styles from './FormStyles.less';
import { toLnglat } from 'react-amap/lib/utils/common';
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['待审核', '已审核', '已驳回'];
const FormItem = Form.Item;
@Form.create()
export default class SelectArea extends Component {
  constructor(props) {
    super(props);
    const self = this;

    this.state = {
      selectedRowKeys: [],
      selectedRows: {},
      position: { lng: 116.402544, lat: 39.928216 },
    };
    this.mapEvents = {
      created: mapinst => {
        //console.log(mapinst);
        self.mapinst = mapinst;
      },
    };
  }
  componentWillReceiveProps(nextProps) {
    let { AreaIds } = nextProps;
    if (
      AreaIds &&
      AreaIds != Object.assign({}, this.props.AreaIds) &&
      JSON.stringify(AreaIds) != '{}'
    ) {
      console.log('A', AreaIds);
      this.setState({
        selectedRowKeys: AreaIds.map(item => item.areaId),
      });
    }
  }

  onSelectChange = (selectedRowKeys, selectedRows) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys, selectedRows });
    this.mapinst.clearMap();
    if (selectedRows.length > 0) {
      selectedRows.map(item => this.drawItem(item));
      let tail = selectedRows[selectedRows.length - 1];
      let { areaName, areaType, areaShape, areaPos } = tail;
      let lngLat = areaPos.lngLat.split(',');
      this.setState({
        position: {
          longitude: parseFloat(lngLat[0]),
          latitude: parseFloat(lngLat[1]),
        },
      });
    }
  };
  drawItem = item => {
    let { areaName, areaType, areaShape, areaPos } = item;
    if (areaShape === '圆') {
      let lngLat = areaPos.lngLat.split(',');
      let center = toLnglat({ lng: lngLat[0], lat: lngLat[1] });
      let option = {
        radius: areaPos.radius * 1000,
        center,
        strokeColor: '#F33', //线颜色
        strokeOpacity: 1, //线透明度
        strokeWeight: 3, //线粗细度
        fillColor: '#ee2200', //填充颜色
        fillOpacity: 0.35, //填充透明度
      };
      this.drawCirCle(option, areaShape);
    } else {
      let lngLat = areaPos.lngLat;
      let centerArray = lngLat.split(';');
      let pathArray = centerArray.map(item => {
        return toLnglat({ lng: item.split(',')[0], lat: item.split(',')[1] });
      });
      let option = {
        path: pathArray,
        strokeColor: '#F33', //线颜色
        strokeOpacity: 1, //线透明度
        strokeWeight: 3, //线粗细度
        fillColor: '#ee2200', //填充颜色
        fillOpacity: 0.35, //填充透明度
      };

      this.drawCirCle(option, areaShape);
    }
  };

  drawCirCle = (option, shape) => {
    if (shape === '圆') {
      const circle = new AMap.Circle(option);

      this.mapinst.add(circle);
    } else {
      const circle = new AMap.Polygon(option);

      this.mapinst.add(circle);
    }
    //this.tool.polygon();
  };
  getFormValue = () => {
    const { form } = this.props;
    const postvalue = {};
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const { entries } = Object;
      for (const [key, value] of entries(fieldsValue)) {
        if (value !== null && value !== undefined) {
          postvalue[key] = value;
        }
      }
    });
    return postvalue;
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch } = this.props;
    const postvalue = this.getFormValue();
    //console.log('values', postvalue);
    dispatch({
      type: 'areaInfo/fetch',
      payload: postvalue,
    });
  };
  submit = () => {
    const { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys.length > 0) {
      const matId = selectedRowKeys[0];
    }
    this.props.setArea(selectedRows);
    this.props.handleModalVisible(false);
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { modalVisible, handleModalVisible, rule } = this.props;
    const data = rule.list.length > 0 ? rule.list : [];
    const { typeCodes, shapeCodes } = rule;
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const columns = [
      {
        title: '区域名称',
        dataIndex: 'areaName',
        editable: true,
      },
      {
        title: '区域类型',
        dataIndex: 'areaType',
      },

      {
        title: '区域形状',
        dataIndex: 'areaShape',
      },

      {
        title: '描述',
        dataIndex: 'shapeDescr',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
      },
    ];
    return (
      <Modal
        title="添加区域"
        visible={modalVisible}
        onOk={this.submit}
        width={1000}
        onCancel={() => handleModalVisible(false)}
      >
        <Form>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              <Form onSubmit={this.handleSearch}>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col span={6} md={4} sm={24}>
                    <FormItem>
                      {getFieldDecorator('areaName', {
                        rules: [{ required: false, message: '请输入区域名称!' }],
                      })(<Input placeholder="区域名称" />)}
                    </FormItem>
                  </Col>
                  <Col span={6} md={4} sm={24}>
                    <FormItem>
                      {getFieldDecorator('areaType', {
                        rules: [{ required: false, message: '请选择区域类型...' }],
                      })(
                        <Select>
                          {typeCodes
                            ? typeCodes.map(item => (
                                <Option key="code" value={item.code}>
                                  {item.name}
                                </Option>
                              ))
                            : null}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={6} md={4} sm={24}>
                    <FormItem>
                      {getFieldDecorator('areaShape', {
                        rules: [{ required: false, message: '请选择区域形状...' }],
                      })(
                        <Select>
                          {shapeCodes
                            ? shapeCodes.map(item => (
                                <Option key="code" value={item.code}>
                                  {item.name}
                                </Option>
                              ))
                            : null}
                        </Select>
                      )}
                    </FormItem>
                  </Col>

                  <Col span={6} md={3} sm={24}>
                    <span className={styles.submitButtons}>
                      <Button
                        type="primary"
                        htmlType="submit"
                        style={{ marginRight: 20 }}
                        onClick={this.handleSearch}
                      >
                        查询
                      </Button>
                    </span>
                  </Col>
                </Row>
              </Form>
            </div>
          </div>
          <div className={styles.mapChart}>
            <Map
              center={this.state.position}
              zoom="13"
              amapkey="74532947bf4c342a9f6e1546fe02325f"
              events={this.mapEvents}
            >
              {/* <Autocomplete
                options={{}}
                onSelect={e => this.selectfunc(e)}
                style={style}
                placeholder="地址查询"
              />
              <MouseTool events={this.toolEvents} />
              {this.renderDiv()}
              {/* <Button className={styles.button1Style}>Areas : {this.state.numbers}</Button> */}
            </Map>
          </div>
          <Table
            rowKey={row => row.areaId}
            rowSelection={rowSelection}
            dataSource={data}
            columns={columns}
          ></Table>
        </Form>
      </Modal>
    );
  }
}
